<script setup>
import axios from "@/axios/index.js";
import { reactive, ref, watch} from "vue";
import {ElMessage} from "element-plus";


let tableData = ref([])
let pagination = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 5
})
let multipleSelection = ref([])

let rowData = ref({
  id: '',
  studentId: '',
  staffId: '',
  startTime: '',
  endTime: '',
  leaveType: '',
  reason: '',
  status: '',
  createdAt: '',
  approvalStatus: ''
})
let loading = ref(true)

function getLeaveTypeText(leaveType) {
  switch (leaveType) {
    case 1:
      return "病假";
    case 2:
      return "事假";
    case 3:
      return "婚假";
    case 4:
      return "其他";
    default:
      return "未知类型";
  }
}

const handleSelectionChange = (value) => {
  multipleSelection = value
}


let currentIndex = ref()
// 审批
async function updateStatus(row, leaveRecordId, approvalStatus,index) {
    currentIndex.value = index
  rowData.value = row
  if (!leaveRecordId) {
    alert('ID不能为空');
    return;
  }

  if (rowData.value.approvalStatus != 0) {
    ElMessage({
      message: '已审批，不能重复审批',
      type: 'warning'
    })
    return;
  }

  axios.put(`/api/v1/admin/verify/studentLeaveApplications`, {
    leaveRecordId,
    approvalStatus
  }, {headers: {'content-type': 'application/json'}}).then(response => {
    ElMessage({
      message: '审批成功',
      type: 'success'
    })
    initData(); // 更新状态后重新加载表格数据
  }).catch(error => {
    ElMessage({
      message: '审批失败',
      type: 'error'
    })
  });

}


watch(tableData,(NewValue,OldValue)=>{
  if (NewValue.length > 0) {
    console.log(NewValue)
    let currentData = reactive({ ...NewValue[currentIndex.value] })
 if (currentData.status == 1){
   console.log("当前学生审批通过")
   axios.post("/api/v1/admin/classes/attendance/insert", {
     studentId: rowData.value.studentId,
     startTime: rowData.value.startTime,
     endTime: rowData.value.endTime,
   }, {headers: {"content-type": "application/json"}});
 }

  }
})

function initData() {
  axios.get("/api/v1/admin/verify/studentLeaveApplications", {
    params: {
      current: pagination.currentPage,
      size: pagination.pageSize
    }
  }).then(resp => {
    if (resp.data.code === 200) {
      tableData.value = resp.data.data.data;
      pagination.total = resp.data.data.total;
      loading.value = false;
    }
  })

}

/**
 * 改变当前页时触发事件
 */
function handleCurrentChange(curPage) {
  pagination.currentPage = curPage
  initData()
}

/**
 * 改变每页数据量大小时触发
 */
function handleSizeChange(curSize) {
  pagination.pageSize = curSize
  initData()
}

initData();

// 监听特定行的 status 变化
// watch(
//     () => rowData.value.status,
//     (newValue, oldValue) => {
//       console.log(newValue, oldValue)
//       if (newValue === 1) {
//         // 请求批量插入考勤记录
//         axios.post("/api/v1/admin/classes/attendance/insert", {
//           studentId: rowData.value.studentId,
//           startTime: rowData.value.startTime,
//           endTime: rowData.value.endTime,
//         }, {headers: {"content-type": "application/json"}});
//       }
//     },
//     {deep: true}
// );


</script>
<template>

  <div class="table">
    <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%;margin-left: auto;text-align: center"
        @selection-change="handleSelectionChange"
        v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="50"/>
      <el-table-column prop="studentName" label="请假人" width="80" align="center"/>
      <el-table-column prop="startTime" label="开始时间" width="150"/>
      <el-table-column prop="endTime" label="截止时间" width="150"/>
      <el-table-column prop="leaveType" label="请假类型" width="80" align="center">
        <template #default="scope">
          <span>{{ getLeaveTypeText(scope.row.leaveType) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="reason" label="请假原因" width="150" align="center" show-overflow-tooltip/>
      <el-table-column prop="createdAt" label="申请时间" width="150" align="center"/>
      <el-table-column label="审批状态" width="120" align="center">
        <template v-slot="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : scope.row.status === 0 ? 'info' : 'danger'">
            {{ scope.row.status === 1 ? '审批已通过' : scope.row.status === 0 ? '未审批' : '审批不通过' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="处理状态" width="120" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.approvalStatus == 0 ? 'info' : 'success'">
            {{ scope.row.approvalStatus == 0 ? '未处理' : '已处理' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="action" label="操作" align="center">
        <template #default="scope">
          <el-link type="success"  v-model="scope.row.status" @click="updateStatus(scope.row,scope.row.id, 1,scope.$index)">审批通过
          </el-link>
          <el-link type="danger" @click="updateStatus(scope.row,scope.row.id, 2)">审批驳回
          </el-link>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        size="small"
        :background="true"
        :page-sizes="[5,10,15,20,30,50,70,100]"
        layout="->,total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>

</template>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

.table {
  margin-left: 30px;
  margin-right: 30px;
  margin-top: 50px;
}

.el-link {
  margin-right: 8px;
}

.el-link .el-icon--right.el-icon {
  vertical-align: text-bottom;
}


</style>